 //
//  QGHomeViewController.swift
//  斯威夫特微博
//
//  Created by youyoumacmini3 on 2017/6/28.
//  Copyright © 2017年 youyoumacmini3. All rights reserved.
//

import UIKit

//定义全局常量。尽量private修饰，否则到处都能访问
 
 // 原创微博可重用cell
fileprivate let originalCellId = "originalCellId"
 // 被转发微博的可重用cell
fileprivate let retweetedCellId = "retweetedCellId"

class QGHomeViewController: QGBaseViewController {


  
    /// 列表视图模型
    fileprivate lazy var listViewModel = QGStatusListViewModel()

    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 注册通知
        NotificationCenter.default.addObserver(self, selector: #selector(browserPhoto), name: NSNotification.Name(rawValue: QGStatusCellBrowserPhotoNotification), object: nil)
    }
    
    deinit {
        // 注销通知
        NotificationCenter.default.removeObserver(self)
    }
    
    /// 浏览照片通知监听方法
    @objc private func browserPhoto(n: Notification) {
        
        // 1. 从通知的 userInfo 提取参数
        guard let selectedIndex = n.userInfo?[QGStatusCellBrowserPhotoSelectedIndexKey] as? Int,
              let urls = n.userInfo?[QGStatusCellBrowserPhotoURLsKey] as? [String],
              let imageViewList = n.userInfo?[QGStatusCellBrowserPhotoImageViewsKey] as? [UIImageView]
            else { return }
        
        // 展现照片浏览控制器
        let vc = HMPhotoBrowserController.photoBrowser(withSelectedIndex: selectedIndex, urls: urls, parentImageViews: imageViewList)
        
        present(vc, animated: true, completion: nil)
        
    }
    
    override func loadData() {

        print("准备刷新")
        
        refreshControl?.beginRefreshing()
        
        DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
            self.listViewModel.loadStatus(pullUp: self.isPullup) { (isSuccess,shouldRefresh) in
                print("加载数据结束")
                //结束刷新控件
                self.refreshControl?.endRefreshing()
                //恢复上拉刷新标记
                self.isPullup = false
                
                //刷新表格
                if shouldRefresh {
                    self.tableView?.reloadData()
                }
            }
        }
        
       
    }
    
    
    
   /*
    /// 加载数据
    override func loadData() {
        QGNetworkManager.shared.statusList { (list, isSuccess) in
            //字典转模型，绑定表格数据
            print(list)
            
        }
        print("开始加载数据\(QGNetworkManager.shared)")
        //模拟延时加载数据 -> dispatch_after
        DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) { 

            //self 是因为闭包中区分语境
            for i in 0..<15 {
                if self.isPullup {
                    self.statusList.append("上拉\(i)")
                }else{
                    //将数据插入到顶部 ->
                    self.statusList.insert(i.description, at: 0)
                }
            }
            //刷新表格
            print("加载数据结束。刷新表格")
            //结束刷新控件
            self.refreshControl?.endRefreshing()
            //恢复上拉刷新标记
            self.isPullup = false
            self.tableView?.reloadData()
        }
    }

*/
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
}


// MARK: - 监听方法
extension QGHomeViewController {
    @objc fileprivate func showFriends() {
        print(#function)
        let vc = ViewController()
        
       // vc.hidesBottomBarWhenPushed = true
        navigationController?.pushViewController(vc, animated:true)
    }
}


// MARK: - 表格数据源方法, 具体的数据源方法实现，不需要super
extension QGHomeViewController {
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return listViewModel.statusList.count
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        // 0. 先取出视图模型。根据视图模型判断可重用cell
        let viewModel = listViewModel.statusList[indexPath.row]
        
        let cellId = (viewModel.status.retweeted_status != nil) ? retweetedCellId : originalCellId

        // 1. 取cell - 本身调用代理方法(如果有)/ 如果没有，找到cell，按照自动布局规则，从上向下计算，找到向下的约束，从而计算动态行高
        let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as! QGStatusCell

        cell.viewModel = viewModel
        
        
        // --- 设置代理
        // 如果用吧block需要在数据源方法中，给每一个cell 设置 block
        // cell.completionBlock = {.....} 每次走这个方法都要创建一大段代码
        // 设置代理只是传递了一个指针地址 - 节省了内存空间
        cell.delegate = self
    
        return cell
    }
    
    // 按视频说此处需要在父类也实现这个方法 然后这里变成 override 才能走这个方法。但是这里自己实现来看并不需要。
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        // 1. 根据 indexPath 获取视图模型
        let vm = listViewModel.statusList[indexPath.row]
        
        // 2. 返回计算好的行高
        return vm.rowHeight
        
    }
}

 
// MARK: - 点击高亮文本代理方法
extension QGHomeViewController: QGStatusCellDelegate {
    func statusCellDidSelectedURLString(cell: QGStatusCell, urlString: String) {
        //print(urlString)
        let vc = QGWebViewController()
        vc.urlString = urlString
        navigationController?.pushViewController(vc, animated: true)
        
    }
}
 
 

// MARK: - 界面
extension QGHomeViewController {
    
    /// 重写父类方法
    override func setTableView() {
    
        super.setTableView()
        
        //设置导航栏（此处无法高亮）
        //navigationItem.leftBarButtonItem = UIBarButtonItem(title: "好友", style: .plain, target: self, action: #selector(showFriends))
        
        //此处我自己写的swift设置UIButton方法。如果调用OC 返回 instanceType的方法，判断不出可选。需要在btn后面加 ‘ :UIButton ’
//        let btn = UIButton(title: "好友", size: 16, nomalColor: #colorLiteral(red: 0.6000000238, green: 0.6000000238, blue: 0.6000000238, alpha: 1), highlightedColor: #colorLiteral(red: 0.9607843161, green: 0.7058823705, blue: 0.200000003, alpha: 1))
//        btn.addTarget(self, action: #selector(showFriends), for: .touchUpInside)
//        navigationItem.leftBarButtonItem = UIBarButtonItem(customView: btn)
        //设置导航栏按钮
        navItem.leftBarButtonItem = UIBarButtonItem(title: "好友", fontSize: 18, target: self, action: #selector(showFriends))
        
        // 注册原型cell
        tableView?.register(UINib(nibName: "QGStatusNormalCell", bundle: nil), forCellReuseIdentifier: originalCellId)
        tableView?.register(UINib(nibName: "QGStatusRetweetedCell", bundle: nil), forCellReuseIdentifier: retweetedCellId)
        
        
        // 设置行高
        //tableView?.rowHeight = UITableViewAutomaticDimension // 自动行高
        //tableView?.estimatedRowHeight = 300
        
        // 取消分割线
        tableView?.separatorStyle = .none
        
        setNaviTitle()
        
    }
    
    fileprivate func setNaviTitle() {
        
        let title = QGNetworkManager.shared.userAccount.screen_name
        
        let button = QGTitleButton(title: title)
        
        button.addTarget(self, action: #selector(clickTitleBtn), for: .touchUpInside)
        
        navItem.titleView = button
    }
    
    
    
    @objc func clickTitleBtn(btn:UIButton) {
        // 设置选中状态
        btn.isSelected = !btn.isSelected
    }
    
    
    
}

